package com.wteam.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wteam.PoJo.DO.Cart;
import com.wteam.PoJo.DO.Goods;
import com.wteam.PoJo.DTO.CartDTO;
import com.wteam.PoJo.DTO.PageQuery;
import com.wteam.PoJo.DTO.upCartDTO;
import com.wteam.PoJo.VO.CartVO;
import com.wteam.mapper.CartMapper;
import com.wteam.Service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wteam.until.Result;
import com.wteam.until.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-16
 */
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Override
    public Result addcart(CartDTO cartDTO) {

        Long userId = UserContext.getUser();

        Goods goods = Db.lambdaQuery(Goods.class)
                .eq(Goods::getId, cartDTO.getGoodsId())
                .one();
        log.info(userId.toString() + "czxc");
        Cart cart = new Cart();
        cart.setGoodsId(cartDTO.getGoodsId());
        cart.setPrice(goods.getPrice());
        cart.setNum(1);
        cart.setUserId(userId);
        save(cart);
        return Result.success("添加成功");
    }

    @Override
    public Result deletecart(List<CartDTO> cartDTO) {
        Long userId = UserContext.getUser();

        List<Long> collect = cartDTO.stream().map(CartDTO::getGoodsId).collect(Collectors.toList());
        LambdaQueryWrapper<Cart> lambdaQueryWrapper = new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId).in(Cart::getGoodsId, collect);
        remove(lambdaQueryWrapper);
        return Result.success("删除成功");
    }

    @Override
    public Result cartshop(PageQuery pageQuery) {

        Page<Cart> CartPage = pageQuery.toMpPage();
        Long userId = UserContext.getUser();
        log.info(userId.toString());
        Page<Cart> Cartpage = lambdaQuery().eq(Cart::getUserId, userId).page(CartPage);
        List<Cart> records = Cartpage.getRecords();
        List<CartVO> cartVOS = BeanUtil.copyToList(records, CartVO.class);
        return Result.success(cartVOS);
    }

    @Override
    public Result upcartshop(List<upCartDTO> upCartDTO) {
        Long userId = UserContext.getUser();
        List<Cart> carts = BeanUtil.copyToList(upCartDTO, Cart.class);
        updateBatchById(carts);
        return Result.success("修改成功");
    }
}
